import auth from '@/plugins/auth'
import router, { constantRoutes, dynamicRoutes } from '@/router'
import { getRouters } from '@/api/menu'
import Layout from '@/layout/index'
import ParentView from '@/components/ParentView'
import InnerLink from '@/layout/components/InnerLink'

// 匹配views里面所有的.vue文件
const modules = import.meta.glob('./../../views/**/*.vue')

const usePermissionStore = defineStore(
  'permission',
  {
    state: () => ({
      routes: [],
      addRoutes: [],
      defaultRoutes: [],
      topbarRouters: [],
      sidebarRouters: []
    }),
    actions: {
      setRoutes(routes) {
        this.addRoutes = routes
        this.routes = constantRoutes.concat(routes)
      },
      setDefaultRoutes(routes) {
        this.defaultRoutes = constantRoutes.concat(routes)
      },
      setTopbarRoutes(routes) {
        this.topbarRouters = routes
      },
      setSidebarRouters(routes) {
        this.sidebarRouters = routes
      },
      // 修改generateRoutes方法
      generateRoutes(roles) {
        return new Promise(resolve => {
          getRouters().then(res => {
            try {
              if (!res.data || !Array.isArray(res.data)) {
                throw new Error('Invalid routes data format');
              }

              // 深度克隆路由数据
              const cloneData = (data) => JSON.parse(JSON.stringify(data));
              const sdata = cloneData(res.data);
              const rdata = cloneData(res.data);
              const defaultData = cloneData(res.data);

              // 预处理路由数据
              const preprocessRoutes = (routes) => {
                return routes.map(route => {
                  // 确保path存在
                  if (!route.path) {
                    route.path = '';
                  }

                  // 处理component
                  if (!route.component) {
                    route.component = 'Layout'; // 默认Layout
                  } else if (route.component.trim() === '') {
                    route.component = { template: '<div></div>' };
                  }

                  // 递归处理子路由
                  if (route.children && route.children.length) {
                    route.children = preprocessRoutes(route.children);
                  } else {
                    delete route.children;
                    delete route.redirect;
                  }

                  return route;
                });
              };

              const processedSdata = preprocessRoutes(sdata);
              const processedRdata = preprocessRoutes(rdata);
              const processedDefaultData = preprocessRoutes(defaultData);

              const sidebarRoutes = filterAsyncRouter(processedSdata);
              const rewriteRoutes = filterAsyncRouter(processedRdata, false, true);
              const defaultRoutes = filterAsyncRouter(processedDefaultData);

              // 过滤并添加动态路由
              const asyncRoutes = filterDynamicRoutes(dynamicRoutes);
              asyncRoutes.forEach(route => {
                try {
                  if (route && route.path) {
                    router.addRoute(route);
                  }
                } catch (e) {
                  console.error('Failed to add dynamic route:', route, e);
                }
              });

              this.setRoutes(rewriteRoutes);
              this.setSidebarRouters([...constantRoutes, ...sidebarRoutes]);
              this.setDefaultRoutes(sidebarRoutes);
              this.setTopbarRoutes(defaultRoutes);
              resolve(rewriteRoutes);
            } catch (error) {
              console.error('Error processing routes:', error);
              resolve([]);
            }
          }).catch(error => {
            console.error('Failed to fetch routes:', error);
            resolve([]);
          });
        });
      }
    }
  })

// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap, lastRouter = false, type = false) {
  if (!asyncRouterMap) return [];

  return asyncRouterMap.filter(route => {
    if (!route) return false;

    try {
      // 处理子路由
      if (type && route.children) {
        route.children = filterChildren(route.children);
      }

      // 处理组件
      if (route.component) {
        if (route.component === 'Layout') {
          route.component = Layout;
        } else if (route.component === 'ParentView') {
          route.component = ParentView;
        } else if (route.component === 'InnerLink') {
          route.component = InnerLink;
        } else if (typeof route.component === 'string' && route.component.trim() !== '') {
          const component = loadView(route.component);
          route.component = component || { template: '<div></div>' };
        } else {
          route.component = { template: '<div></div>' };
        }
      } else {
        route.component = { template: '<div></div>' };
      }

      // 递归处理子路由
      if (route.children && route.children.length) {
        route.children = filterAsyncRouter(route.children, route, type);
      } else {
        delete route.children;
        delete route.redirect;
      }

      return true;
    } catch (error) {
      console.error('Error processing route:', route, error);
      return false;
    }
  });
}

function filterChildren(childrenMap, lastRouter = false) {
  if (!childrenMap || !Array.isArray(childrenMap)) return [];

  let children = [];
  childrenMap.forEach((el, index) => {
    if (!el) return;

    try {
      if (el.children && el.children.length) {
        if (el.component === 'ParentView' && !lastRouter) {
          el.children.forEach(c => {
            if (!c.path) c.path = '';
            c.path = el.path + '/' + c.path;
            if (c.children && c.children.length) {
              children = children.concat(filterChildren(c.children, c));
              return;
            }
            children.push(c);
          });
          return;
        }
      }

      if (lastRouter) {
        if (!el.path) el.path = '';
        el.path = lastRouter.path + '/' + el.path;
        if (el.children && el.children.length) {
          children = children.concat(filterChildren(el.children, el));
          return;
        }
      }

      children.push(el);
    } catch (error) {
      console.error('Error processing child route:', el, error);
    }
  });
  return children;
}

// 动态路由遍历，验证是否具备权限
export function filterDynamicRoutes(routes) {
  const res = []
  routes.forEach(route => {
    if (route.permissions) {
      if (auth.hasPermiOr(route.permissions)) {
        res.push(route)
      }
    } else if (route.roles) {
      if (auth.hasRoleOr(route.roles)) {
        res.push(route)
      }
    }
  })
  return res
}

export const loadView = (view) => {
  if (!view || typeof view !== 'string') {
    console.warn('Invalid view path:', view);
    return { template: '<div></div>' };
  }

  // 标准化路径，将反斜杠替换为正斜杠
  const normalizedView = view.replace(/\\/g, '/');

  try {
    for (const path in modules) {
      const dir = path.split('views/')[1]?.split('.vue')[0];
      if (dir && dir.replace(/\\/g, '/') === normalizedView) {
        return () => modules[path]();
      }
    }

    console.warn(`Component ${normalizedView} not found in views directory`);
    return { template: '<div></div>' };
  } catch (error) {
    console.error('Error loading view:', normalizedView, error);
    return { template: '<div></div>' };
  }
};

export default usePermissionStore
